package cn.edu.gzhu.workOrderManagement.intercepter;

import cn.edu.gzhu.workOrderManagement.constants.MessageConstant;
import cn.edu.gzhu.workOrderManagement.enumeration.UserAuthorityEnum;
import cn.edu.gzhu.workOrderManagement.mapper.UserMapper;
import cn.edu.gzhu.workOrderManagement.mapper.WorkOrderMapper;
import cn.edu.gzhu.workOrderManagement.pojo.dto.workOrder.WorkOrderRepeatDto;
import cn.edu.gzhu.workOrderManagement.pojo.entity.WorkOrder;
import cn.edu.gzhu.workOrderManagement.util.ResponseUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.stream.Collectors;

@Component
@Slf4j
//总部商务可以重诉工单
//客户可以重诉自己的工单
public class WorkOrderRepeatInterceptor implements HandlerInterceptor {
    @Autowired
    WorkOrderMapper workOrderMapper;
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Claims claims = (Claims)request.getAttribute("claims");
        UserAuthorityEnum authority = UserAuthorityEnum.value2Object( claims.get("authority").toString());
        String username = claims.get("username").toString();
        log.info("{}正在重诉工单", authority);
        if(!authority.equals(UserAuthorityEnum.HEAD_BUSINESS)&&!authority.equals(UserAuthorityEnum.CLIENT)){
            ResponseUtil.failResponse(response, MessageConstant.PERMISSION_DENIED);
            return false;
        }
        // 客户只能重诉自己的工单
        if(authority.equals(UserAuthorityEnum.CLIENT)){
            String body = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
            WorkOrderRepeatDto workOrderRepeatDto = JSONUtil.toBean(body, WorkOrderRepeatDto.class);
            QueryWrapper<WorkOrder> workOrderQueryWrapper= new QueryWrapper<>();
            workOrderQueryWrapper.eq("uuid", workOrderRepeatDto.getUuid());
            WorkOrder workOrder = workOrderMapper.selectOne(workOrderQueryWrapper);
            if(workOrder.getRequestUser().equals(username)){
                ResponseUtil.failResponse(response, MessageConstant.PERMISSION_DENIED);
                return false;
            }
        }
        return true;
    }



}
